package com.eclipse.training.extensions.actions;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.ui.PlatformUI;

import com.eclipse.training.extensions.Activator;
import com.eclipse.training.extensions.editors.TrainingPageEditor;
import com.eclipse.training.models.BaseModelElement;
import com.eclipse.training.models.ModelContainer;
import com.eclipse.training.models.ModelElement;

public class AddAction extends Action {
	boolean isContainer = false;

	public AddAction(boolean isContainer) {
		this.isContainer = isContainer;

		setImageDescriptor(Activator.getDefault().getImageDescriptor(
				Activator.IMAGE_ADD));
		if (isContainer) {
			setText(Messages.AddAction_0);
			setToolTipText(Messages.AddAction_1);
		} else {
			setText(Messages.AddAction_2);
			setToolTipText(Messages.AddAction_3);
		}
	}

	@Override
	public void run() {

		/*
		 * Get the selection from the active editor
		 */
		TrainingPageEditor editor = (TrainingPageEditor) PlatformUI
				.getWorkbench().getActiveWorkbenchWindow().getActivePage()
				.getActiveEditor();
		TreeViewer viewer = editor.getViewer();
		IStructuredSelection sel = (IStructuredSelection) viewer.getSelection();
		ModelContainer container = (ModelContainer) sel.getFirstElement();

		BaseModelElement element;

		/*
		 * Update the model
		 */
		if (isContainer)
			element = new ModelContainer(Messages.AddAction_4);
		else
			element = new ModelElement(Messages.AddAction_5, Messages.AddAction_6);

		container.getElements().add(element);

		/*
		 * Refresh the viewer and set the editor as dirty
		 */
		viewer.refresh(true);
		editor.treeModified();

		super.run();
	}
}
